package com.zrc.japktool.ui;

import com.zrc.japktool.ui.view.RichTextFXLogView;
import com.zrc.japktool.ui.view.WebLogView;
import com.zrc.japktool.util.TaskLog;
import com.zrc.japktool.apk.keytool.KeyTool;
import com.zrc.japktool.util.FileUtil;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import com.zrc.japktool.util.DialogUtil;
import javafx.stage.Stage;

import java.io.File;

public class Tab3Controller_KeyStore {

    private boolean isRunner = false;
    @FXML
    private TextField outputDir_TextField;
    @FXML
    private RichTextFXLogView logView;
    @FXML
    private TextField inputAlias_TextField;
    @FXML
    private TextField inputKsPass_TextField;
    @FXML
    private TextField inputKeyPass_TextField;

    private TaskLog log = new TaskLog() {

        @Override
        public void info(String msg) {logView.info(msg);}

        @Override
        public void warn(String msg) {logView.warn(msg);}

        @Override
        public void debug(String msg) {logView.debug(msg);}

        @Override
        public void error(String msg) {logView.error(msg);}

        @Override
        public void tip(String msg) {logView.tip(msg);}

    };

    @FXML
    public void initialize() {
        logView.tip("等待操作...");// 初始化日志区域
    }

    @FXML
    private void selectOutputDir() {
        DirectoryChooser dirChooser = new DirectoryChooser();
        dirChooser.setTitle("选择输出目录");

        // 设置初始目录为桌面（兼容 Windows/macOS/Linux）
        File desktopDir = new File(System.getProperty("user.home"), "Desktop");
        if (desktopDir.exists()) {
            dirChooser.setInitialDirectory(desktopDir);
        } else {
            // 如果 Desktop 目录不存在（如某些 Linux 环境），则回退到用户主目录
            dirChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        }

        File selectedFile = dirChooser.showDialog(null);
        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            outputDir_TextField.setText(filePath);
            logView.tip("已选择输出目录: " + filePath);
        } else {
            logView.tip("选择输出目录已取消");
        }
    }

    @FXML
    private void startTask() {
        if (isRunner) {
            DialogUtil.showInfoDialog((Stage)logView.getScene().getWindow(),"温馨提示！","当前任务正在进行: 请认真等待...");
            logView.error("当前任务正在进行: 请认真等待...");
            return;
        }

        String outputDir = outputDir_TextField.getText().replace("\\", "/");
        if (outputDir.isEmpty()) {
            logView.error("错误: 请先选择输出目录...");
            return;
        }

        String inputAlias = inputAlias_TextField.getText();
        if (inputAlias.isEmpty()) {
            logView.error("错误: 请先输入Alias...");
            return;
        }

        String inputKsPass = inputKsPass_TextField.getText();
        if (inputKsPass.isEmpty()) {
            logView.error("错误: 请先输入ks-pass...");
            return;
        }

        String inputKeyPass = inputKeyPass_TextField.getText();
        if (inputKeyPass.isEmpty()) {
            logView.error("错误: 输入key-pass...");
            return;
        }

        // 创建一个Task来执行耗时操作
        Task<Void> task = new Task<>() {
            @Override
            protected Void call() {
                logView.clear();
                isRunner = true;
                logView.info("创建签名文件: " + outputDir);
                try {
                    KeyTool keyTool = new KeyTool(log);
                    keyTool.generateKeystore(
                            (outputDir + "/" + inputAlias + ".keystore"),
                            inputAlias,
                            inputKsPass.trim(),
                            inputKeyPass.trim(),
                            100,
                            "CN=Android Developer, OU=Mobile, O=Company, L=Beijing, ST=Beijing, C=CN");
                    logView.info("创建签名文件: 成功...");
                } catch (Exception e) {
                    logView.error("创建签名文件: 失败...");
                    logView.error("创建签名文件: 失败问题:" + e.getMessage());
                    e.printStackTrace();
                }
                isRunner = false;
                return null;
            }
        };

        // 设置任务失败时的处理
        task.setOnFailed(event -> {
            isRunner = false;
            Throwable exception = task.getException();
            Platform.runLater(() -> {
                logView.error("任务执行失败: " + exception.getMessage());
                exception.printStackTrace();
            });
        });

        // 启动后台线程执行任务
        new Thread(task).start();
    }
}